<template>
  <Layout>
    <div class="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 文章头部 -->
      <header class="mb-8">
        <div class="flex items-center text-sm text-gray-500 mb-4">
          <Link
            :href="`/categories/${post.category.slug}`"
            class="hover:text-blue-600"
          >
            {{ post.category.name }}
          </Link>
          <span class="mx-2">•</span>
          <span>{{ formatDate(post.published_at) }}</span>
          <span class="mx-2">•</span>
          <span>{{ post.reading_time }} 分钟阅读</span>
          <span class="mx-2">•</span>
          <span>{{ post.views_count }} 次浏览</span>
        </div>

        <h1 class="text-3xl font-bold text-gray-900 mb-4">{{ post.title }}</h1>

        <div class="flex items-center justify-between">
          <div v-if="post.user" class="flex items-center">
            <img
              :src="post.user?.avatar_url || `https://ui-avatars.com/api/?name=${post.user?.name || 'User'}`"
              :alt="post.user?.name || 'User'"
              class="w-10 h-10 rounded-full mr-3"
            />
            <div>
              <Link
                :href="`/authors/${post.user?.username || '#'}`"
                class="font-medium text-gray-900 hover:text-blue-600"
              >
                {{ post.user?.name || 'Anonymous' }}
              </Link>
              <p class="text-sm text-gray-500">{{ formatDate(post.published_at) }}</p>
            </div>
          </div>

          <div class="flex items-center space-x-4">
            <span class="flex items-center text-gray-500">
              ❤️ {{ post.likes_count }}
            </span>
            <span class="flex items-center text-gray-500">
              💬 {{ post.comments_count }}
            </span>
          </div>
        </div>

        <!-- 标签 -->
        <div v-if="post.tags.length > 0" class="mt-4">
          <Link
            v-for="tag in post.tags"
            :key="tag.id"
            :href="`/tags/${tag.slug}`"
            class="inline-block bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm mr-2 hover:bg-blue-200"
          >
            #{{ tag.name }}
          </Link>
        </div>
      </header>

      <!-- 特色图片 -->
      <div v-if="post.featured_image" class="mb-8">
        <img
          :src="`/storage/${post.featured_image}`"
          :alt="post.title"
          class="w-full rounded-lg shadow-md"
        />
      </div>

      <!-- 文章内容 -->
      <article class="prose prose-lg max-w-none mb-12" v-html="post.content"></article>

      <!-- 评论部分 -->
      <section class="mt-12">
        <h3 class="text-2xl font-bold mb-6">评论 ({{ post.comments.length }})</h3>

        <!-- 评论表单 -->
        <div v-if="$page.props.auth.user" class="mb-8">
          <form @submit.prevent="submitComment" class="bg-white p-6 rounded-lg shadow-md">
            <div class="mb-4">
              <label class="block text-sm font-medium text-gray-700 mb-2">
                添加评论
              </label>
              <textarea
                v-model="commentForm.content"
                rows="4"
                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                placeholder="写下你的想法..."
                required
              ></textarea>
            </div>
            <button
              type="submit"
              :disabled="commentForm.processing"
              class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 disabled:opacity-50"
            >
              {{ commentForm.processing ? '提交中...' : '提交评论' }}
            </button>
          </form>
        </div>

        <div v-else class="mb-8 p-4 bg-gray-100 rounded-lg text-center">
          <p class="text-gray-600">
            请 <Link href="/login" class="text-blue-600 hover:underline">登录</Link> 后发表评论
          </p>
        </div>

        <!-- 评论列表 -->
        <div class="space-y-6">
          <div
            v-for="comment in post.comments"
            :key="comment.id"
            class="bg-white p-6 rounded-lg shadow-md"
          >
            <div class="flex items-start">
              <img
                :src="comment.user?.avatar_url || 'https://ui-avatars.com/api/?name=' + comment.author_name"
                :alt="comment.author_name"
                class="w-10 h-10 rounded-full mr-3"
              />
              <div class="flex-1">
                <div class="flex items-center justify-between mb-2">
                  <div>
                    <h4 class="font-medium text-gray-900">
                      {{ comment.author_name }}
                    </h4>
                    <p class="text-sm text-gray-500">{{ formatDate(comment.created_at) }}</p>
                  </div>
                  <button
                    v-if="canDeleteComment(comment)"
                    @click="deleteComment(comment.id)"
                    class="text-red-600 hover:text-red-800 text-sm"
                  >
                    删除
                  </button>
                </div>
                <p class="text-gray-700">{{ comment.content }}</p>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- 相关文章 -->
      <section v-if="relatedPosts.length > 0" class="mt-12">
        <h3 class="text-2xl font-bold mb-6">相关文章</h3>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <article
            v-for="related in relatedPosts"
            :key="related.id"
            class="bg-white rounded-lg shadow-md overflow-hidden"
          >
            <img
              v-if="related.featured_image"
              :src="`/storage/${related.featured_image}`"
              :alt="related.title"
              class="w-full h-40 object-cover"
            />
            <div class="p-4">
              <h4 class="font-semibold mb-2">
                <Link
                  :href="`/posts/${related.slug}`"
                  class="hover:text-blue-600"
                >
                  {{ related.title }}
                </Link>
              </h4>
              <p class="text-sm text-gray-600">{{ truncate(related.excerpt, 100) }}</p>
            </div>
          </article>
        </div>
      </section>
    </div>
  </Layout>
</template>

<script>
import { Link } from '@inertiajs/inertia-vue3'
import { Inertia } from '@inertiajs/inertia'
import Layout from '../../Components/Layout.vue'

export default {
  name: 'BlogShow',
  components: {
    Layout,
    Link
  },
  props: {
    post: Object,
    relatedPosts: Array
  },
  data() {
    return {
      commentForm: {
        content: '',
        processing: false
      }
    }
  },
  methods: {
    submitComment() {
      this.commentForm.processing = true

      Inertia.post(`/posts/${this.post.id}/comments`, {
        content: this.commentForm.content
      }, {
        onSuccess: () => {
          this.commentForm.content = ''
        },
        onFinish: () => {
          this.commentForm.processing = false
        }
      })
    },
    deleteComment(commentId) {
      if (confirm('确定要删除这条评论吗？')) {
        Inertia.delete(`/comments/${commentId}`)
      }
    },
    canDeleteComment(comment) {
      const user = this.$page.props.auth.user
      return user && (user.id === comment.user_id || user.role === 'admin')
    },
    formatDate(date) {
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric'
      })
    },
    truncate(text, length) {
      if (!text) return ''
      return text.length > length ? text.substring(0, length) + '...' : text
    }
  }
}
</script>